package cfgReader

import (
	"fmt"
	path "path/filepath"
	"strings"
)

// 数据表预处理过程
type TablePreProcess interface {
	TableName() string
	Process(t *Table)
}

// 静态数据管理器
type SDataMgr struct {
	//全部已加载的表 [表名]表实例
	tables     map[string]*Table
	preUseFunc map[string]TablePreProcess
	sdataPath  string
}

// 生成数据表路径
var makeTablePath = func(sdataPath, tabName string) string {
	tabName = strings.ToLower(tabName)
	tabPath := fmt.Sprintf("%s.json.txt", tabName)

	re := path.Join(sdataPath, tabPath)
	//YsDbg.Infof(nil,"TablePath:%v",re)
	return re
}

// 初始化数据表
// 非线程安全
func (myself *SDataMgr) InitTable(tabName string, newRow NewRowFunc) error {

	//已经初始化过
	if myself.tables[tabName] != nil {
		return nil
	}

	//加载表
	table := NewTable()
	err := table.Load(newRow, makeTablePath(myself.sdataPath, tabName))
	if err != nil {
		return err
	}

	//缓存Tab
	myself.tables[tabName] = table

	//预处理
	preProcess := myself.preUseFunc[tabName]
	if preProcess != nil {
		preProcess.Process(table)
	}

	return nil
}

func (myself *SDataMgr) RegTableProcess(preProcess TablePreProcess) {
	myself.preUseFunc[preProcess.TableName()] = preProcess
}

// 获取整张配置表
func (myself *SDataMgr) GetTable(tableName string) *Table {
	return myself.tables[tableName]
}

// 新建SDataMgr对象
func NewSDataMgr(sdataPath string) *SDataMgr {
	re := &SDataMgr{}
	re.tables = make(map[string]*Table)
	re.preUseFunc = make(map[string]TablePreProcess)
	re.sdataPath = sdataPath
	return re
}
